<?php

namespace App\Services;


use App\Enums\PayMethod;
use App\Exceptions\InvalidRequestException;
use App\Models\Order;
use Illuminate\Support\Carbon;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Pay;
use Illuminate\Support\Str;

class PayService
{


    /**
     * 扫码支付
     * @param Order $order
     * @return mixed
     * @throws InvalidRequestException
     */
    public function scan(Order $order): mixed
    {
        try {
            Pay::config(config('pay'));
            //订单生成成功，调用支付
            if ($order->pay_method == PayMethod::WECHAT) {
                $pay_param = [
                    'out_trade_no' => $order->order_no,
                    'description' => Str::substr($order->project->title, 0, 40),
                    'amount' => [
                        'total' => $order->money * 100,//单位：分
                    ],
                    'time_expire' => Carbon::parse($order->pay_expired_time)->toRfc3339String(),
                ];
                $result = Pay::wechat()->scan($pay_param);
                if (isset($result->message)) {
                    throw new InvalidRequestException($result->message ?? '支付调用，请重试');
                }
                $pay_address = $result->code_url;
            } else {
                //这里是返回html
                $pay_param = [
                    'out_trade_no' => $order->order_no,
                    'total_amount' => $order->money,
                    'subject' => Str::substr($order->project->title, 0, 40),
                    'product_code' => 'FAST_INSTANT_TRADE_PAY',
                    'time_expire' => $order->pay_expired_time->toDateTimeString()
                ];
                $pay_address = Pay::alipay()->web($pay_param);
                $pay_address = $pay_address->getBody()->getContents();
            }
            $order->pay_param = json_encode($pay_param, JSON_UNESCAPED_UNICODE);
            $order->pay_address = $pay_address;
            $order->save();
            return $pay_address;
        } catch (ContainerException $e) {
            throw new InvalidRequestException('支付调用失败：', $e->getMessage());
        }
    }

}
